package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.serivce.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Employee record) {
        if (record.getId() == null) {
            //加密
            String password = record.getPassword();
            Md5Hash hash = new Md5Hash(password, record.getUsername(), 2);
            //设置加密之后的密码
            record.setPassword(hash.toString());
            //默认新增员工在职状态
            record.setState(true);
            //保存操作
            mapper.insert(record);
        }else {
            mapper.deleteRelation(record.getId());
            mapper.updateByPrimaryKey(record);
        }
        //维护关系
        for (Role role : record.getRoles()) {
            mapper.insertRelation(record.getId(),role.getId());
        }
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(EmployeeQueryObject qo) {

        Integer total = mapper.count(qo);
        if (total > 0) {
            List<Employee> rows = mapper.query(qo);

            return new PageResult(total,rows);
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }

    @Override
    public Boolean selectByUsername(String username, Long empId) {
        Employee employee = mapper.selectByPrimaryKey(empId);
        int i = mapper.validateName(username);
        //当前数据库中没有重复或者其id对应的用户名和当前用户名相同,则证明可以
        if (i == 0 || employee.getUsername().equals(username)){
            return true;
        }
        return false;//数据库存在相同
    }

    @Override
    public void changeState(Long id) {
        mapper.changeStateById(id);
    }

    @Override
    public void updatePassword(Employee emp) {
        mapper.updatePasswordById(emp.getId(),emp.getPassword());
    }

    @Override
    public Employee slelectByUsernameInfo(String principal) {

        return  mapper.slelectByUsernameInfo(principal);
    }

    @Override
    public List<Employee> selectAll() {
        return mapper.selectAll();
    }

}
